package brinaryTree;

import java.util.ArrayDeque;
import java.util.Deque;

public class N116_PopulatingNextRightPointersInEachNode {
    private class Node {
        public int val;
        public Node left;
        public Node right;
        public Node next;

        public Node() {
        }

        public Node(int _val) {
            val = _val;
        }

        public Node(int _val, Node _left, Node _right, Node _next) {
            val = _val;
            left = _left;
            right = _right;
            next = _next;
        }
    }

    public Node connect(Node root) {
        Deque<Node> deque = new ArrayDeque<>();
        if (root != null) deque.add(root);
        Node preNode = null, node;

        while (!deque.isEmpty()) {
            int size = deque.size();
            for (int i = 0; i < size; i++) {
                if (i == 0) {
                    preNode = deque.pop();
                    node = preNode;
                } else {
                    node = deque.pop();
                    preNode.next = node;
                    preNode = preNode.next;
                }
                if (node.left != null) deque.add(node.left);
                if (node.right != null) deque.add(node.right);
            }
        }

        return root;
    }
}
